#ifndef QHTTPHELPER_H
#define QHTTPHELPER_H

#include <QObject>

#include <functional>

#include <QtNetwork>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QNetworkRequest>
#include <QtConcurrent/QtConcurrent>
#include <QFuture>
#include <QByteArray>
#include <QDebug>

class QHttpHelper : public QObject
{
    Q_OBJECT
public:
    explicit QHttpHelper(QObject *parent = nullptr);

    /**
     * @brief syncGet    http get 的同步方式
     * @param geturl     请求地址
     * @param paramList  请求的参数列表
     * @param timeout    超时
     * @return           byteArray 最终请求到的结果
     */
    QByteArray syncGet(QString geturl, QStringList paramList = QStringList(),int timeout = 1000);

    template<typename T>
    struct isFunctor : std::false_type {
    };
    template<typename L, typename R, typename... Args>
    struct isFunctor<R (L::*)(Args...)> : std::true_type {
};
    template<typename L>
    struct isLambda : isFunctor<decltype(&L::operator())> {
    };

    template<typename L>
    /**
     * @brief asyncGet
     * @param geturl
     * @param paramList
     * @param lambda
     * 异步调用的HTTP get模式  参数1 url 参数2 请求的参数列表 参数3 对返回结果进行处理的lambda表达式
     */
    void asyncGet(QString geturl, QStringList paramList, L lambda)
    {
        //        qDebug() << __LINE__ << geturl;
        QStringList params = paramList;

        if(params.size() > 2)
            qSort(params.begin(), params.end());
        auto param = params.join("&");

        auto url = geturl + param;
        qDebug() << __LINE__ << url << QThread::currentThread();

        QtConcurrent::run(QThreadPool::globalInstance(),[=](){
            auto rec = get(url);
            if(lambda)
                lambda(QByteArray(rec));
        });
    }

signals:

public slots:

private:
    QByteArray get(const QString &strUrl, int timeout = 1000);
};

#endif // QHTTPHELPER_H
